// pages/waiter/billing/billing.js
var request = require("../../../utils/request.js")
var config = require("../../../config.js")
var util = require("../../../utils/MD5.js")
const common = require('../../../common/js/common.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        setTag: false,
        ztList: [],
        waiter: {},
        Labellist: [],
        tempMember: {
            C_MB_NO: "",
        },
        showMemberChoose: false,
        keywords: "",
        num: "",
        cwf: 0,
        labelPrice: "",
        pageIndex: 1,
        pageSize: 100,
        labelName: "",
        remark: "",

        tids: '', // 桌台号
        num: '', // 用餐人数
    },
    // onShow
    onShow: function () {
        wx.getStorage({
            key: 'zt_info',
            success: res => {
                this.data.Tablesinfo = res.data[0];
                this.setData({
                    ztList: res.data,
                })
            },
        })

        this.data.billingTable = wx.getStorageSync("order-table");

        wx.getStorage({
            key: 'waiter',
            success: res => {
                this.setData({
                    waiter: res.data,
                })
            },
        })

        wx.getStorage({
            key: 'label',
            success: res => {
                this.data.label = res.data;
            },
        })

        wx.getStorage({
            key: 'C_SHOP_NO',
            success: res => {
                this.data.ShopNo = res.data;
                this.getLabelInfo();
            },
        })
    },
    // 设置用餐人数
    setNum(ev) {
        if (ev.detail.value) {
            if (parseInt(ev.detail.value) < 10000) {
                this.setData({
                    num: ev.detail.value
                })
            } else {
                this.setData({
                    num: 9999
                })
            }
        } else {
            this.data.num = 0;
        }
    },

    chooseMember() {
        this.setData({
            showMemberChoose: true
        })
    },

    sureMember() {
        if (this.data.tempMember.C_MB_NO) {
            this.setData({
                member: this.data.tempMember,
                showMemberChoose: false,
            })
        } else {
            this.hideMember();
        }
    },

    clearMember() {
        this.setData({
            tempMember: {
                C_MB_NO: "",
            },
            member: null
        })
    },

    /**
     * 获取会员列表
     */
    getMenberList() {
        if (!/^1\d{10}/g.test(this.data.keywords)) {
            wx.showModal({
                title: '提示',
                content: '请填写正确的手机号码',
                showCancel: false,
            })
            return;
        }
        var str = `ShopNo&keywords&gradeId&pageIndex&pageSize=${this.data.ShopNo}*${this.data.keywords}*0*${this.data.pageIndex}*${this.data.pageSize}`;
        var md5 = util.md5(str);
        wx.showLoading({
            title: '加载中',
        })
        var data = {
            bNo: 1204,
            ShopNo: this.data.ShopNo,
            keywords: this.data.keywords,
            gradeId: 0,
            pageIndex: this.data.pageIndex,
            pageSize: this.data.pageSize,
            keytype: -1,
            MD5: md5.toUpperCase()
        };

        wx.request({
            url: config.requestUrl,
            data,
            success: res => {
                var d = res.data.replace(/\(|\)/g, "");
                var t = JSON.parse(d);
                if (t.mebdt.length > 0) {
                    for (var i = 0; i < t.mebdt.length; i++) {
                        if (t.mebdt[i].C_MB_NAME.length > 20) {
                            t.mebdt[i].C_MB_NAME = t.mebdt[i].C_MB_NAME.substr(0, 20) + "..."
                        }

                        if (t.mebdt[i].C_MB_PIC) {
                            t.mebdt[i].C_MB_PIC = config.FilePath + t.mebdt[i].C_MB_PIC;
                        }
                    }
                    // wx.setStorage({
                    //     key: 'member',
                    //     data: t.mebdt[0],
                    // })
                    this.setData({
                        tempMember: t.mebdt[0],
                    })
                } else {
                    wx.showModal({
                        title: '提示',
                        content: '抱歉，暂无会员信息',
                        showCancel: false,
                    })
                }
                wx.hideLoading()
            }
        })
    },

    hideMember() {
        this.setData({
            showMemberChoose: false
        })
    },

    chooseWaiter() {
        wx.navigateTo({
            url: '/pages/waiter/chooseWaiter/chooseWaiter',
        })
    },

    def() {

    },

    showSet() {
        this.setData({
            setTag: true,
        })
    },

    // 开桌1
    open() {
        this.data.billingTable[this.data.billingTable.length - 1].PeopleCount = this.data.num;
        wx.setStorageSync("order-table", this.data.billingTable);
        if (this.data.num <= 0) {
            wx.showModal({
                title: '提示',
                content: '请填写使用人数',
                showCancel: false,
            })
            return;
        }

        var C_MB_NO = "";
        var C_MB_PHONE = "";
        if (this.data.member) {
            C_MB_NO = this.data.member.C_MB_NO;
            C_MB_PHONE = this.data.member.C_MB_PHONE
        }

        var ids = [];
        for (var i = 0; i < this.data.ztList.length; i++) {
            ids.push(this.data.ztList[i].ID);
        }
        var str = `tids&Remark&Ponut&C_MB_NO&C_MB_PHONE&lcodes&lprice&wids&wname&CWF&ShopNo=${ids.join(",")}*${this.data.remark}*${this.data.num}*${C_MB_NO}*${C_MB_PHONE}*${this.data.label.Code || ""}*${this.data.label.N_Label_Price || 0}*${this.data.waiter.n_ss_id || ""}*${this.data.waiter.c_name || ""}*${this.data.cwf}*${this.data.ShopNo}`
        var md5 = util.md5(str);
        var data = {
            bNo: 2203,
            tids: ids.join(","),
            Remark: this.data.remark,
            Ponut: this.data.num,
            C_MB_NO,
            C_MB_PHONE,
            lcodes: this.data.label.Code || "",
            lprice: this.data.label.N_Label_Price || 0,
            wids: this.data.waiter.n_ss_id || "",
            wname: this.data.waiter.c_name || "",
            CWF: this.data.cwf,
            ShopNo: this.data.ShopNo,
            MD5: md5.toUpperCase()
        };

        request(data, data => {
            wx.showToast({
                title: data.msg,
                icon: 'none'
            })
            setTimeout(function() {
                wx.navigateBack({
                    delta: 1,
                })
            }, 500)
        })
    },
    // 开桌并点菜
    toOrderFunc() {
        this.data.billingTable[this.data.billingTable.length - 1].PeopleCount = this.data.num;
        wx.setStorageSync("order-table", this.data.billingTable);
        if (this.data.num <= 0) {
            wx.showModal({
                title: '提示',
                content: '请填写使用人数',
                showCancel: false,
            })
            return;
        }

        var ids = [];
        for (var i = 0; i < this.data.ztList.length; i++) {
            ids.push(this.data.ztList[i].ID);
        }

        var name = [];
        var code = [];
        var price = 0;

        for (var i = 0; i < this.data.Labellist.length; i++) {
            if (this.data.Labellist[i].checked) {
                name.push(this.data.Labellist[i].C_Label_Name)
                code.push(this.data.Labellist[i].Code)
                price += this.data.Labellist[i].N_Label_Price
            }
        }

        if (this.data.remark) {
            name.push(this.data.remark)
        }

        var C_MB_NO = "";
        var C_MB_PHONE = "";
        if (this.data.member) {
            C_MB_NO = this.data.member.C_MB_NO;
            C_MB_PHONE = this.data.member.C_MB_PHONE
        }

        wx.showLoading({
            title: '正在处理',
        })

        var str = `tids&Remark&Ponut&C_MB_NO&C_MB_PHONE&lcodes&lprice&wids&wname&CWF&ShopNo=${ids.join(",")}*${name.join(",")}*${this.data.num}*${C_MB_NO}*${C_MB_PHONE}*${code.join(",")}*${price}*${this.data.waiter.n_ss_id || ""}*${this.data.waiter.c_name || ""}*${this.data.cwf}*${this.data.ShopNo}`
        var md5 = util.md5(str);
        var data = {
            bNo: 2204,
            tids: ids.join(","),
            Remark: name.join(","),
            Ponut: this.data.num,
            C_MB_NO,
            C_MB_PHONE,
            lcodes: code.join(","),
            lprice: price,
            wids: this.data.waiter.n_ss_id || "",
            wname: this.data.waiter.c_name || "",
            CWF: this.data.cwf,
            ShopNo: this.data.ShopNo,
            MD5: md5.toUpperCase()
        };

        request(data, res => {
            if (res.code === "100") {
                this.toOrder();
            } else {
                wx.showModal({
                    title: '提示',
                    content: res.msg,
                    showCancel: false,
                    success: (res) => {
                        console.log(res)
                        wx.navigateBack({
                            delta: 1,
                        })
                    }
                })
                wx.hideLoading()
            }
        })
    },

    toOrder() {
        var arr = [];
        wx.getStorage({
            key: 'Tablesinfo',
            success: res => {
                var flag = false;
                for (var i = 0; i < res.data.length; i++) {
                    if (res.data[i].ID == this.data.Tablesinfo.ID) {
                        var gList = [];
                        var order = [];
                        if (res.data[i].gList) {
                            gList = res.data[i].gList
                            order = res.data[i].order
                        }
                        this.data.Tablesinfo.gList = gList;
                        this.data.Tablesinfo.order = order;
                        res.data[i] = this.data.Tablesinfo;
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    res.data.push(this.data.Tablesinfo)
                }
                this.linkToOrder(res.data);
            },
            fail: () => {
                arr.push(this.data.Tablesinfo);
                this.linkToOrder(arr);
            }
        })
    },

    linkToOrder(arr) {
        var url = "";
        if (this.data.member) {
            url = "&mebno=" + this.data.member.C_MB_NO;
        }
        wx.setStorage({
            key: 'Tablesinfo',
            data: arr,
            success: res => {
                wx.redirectTo({
                    url: '/pages/waiter/order/order?TableID=' + this.data.Tablesinfo.ID + url,
                })
            }
        })
    },

    /**
     * 设置标签名称
     */
    setLabelName(ev) {
        this.setData({
            labelName: ev.detail.value,
        })
    },

    /**
     * 设置标签价格
     */
    setLabePrice(ev) {
        var p = ev.detail.value
        if (ev.detail.value.indexOf(".") != -1) {
            if (ev.detail.value.indexOf(".") == 0) {
                ev.detail.value = "0" + ev.detail.value;
            }
            p = ev.detail.value.match(/\d+\.\d{0,2}/g)[0];
        }
        this.setData({
            labelPrice: p,
        })
    },

    submitLabel() {
        if (!this.data.labelName) {
            wx.showModal({
                title: '提示',
                content: '请填写标签名称',
                showCancel: false,
            })

            return;
        }

        if (!this.data.labelPrice) {
            wx.showModal({
                title: '提示',
                content: '请填写标签价格',
                showCancel: false,
            })

            return;
        }
        var str = `LABLE_NAME&LABLE_PRICE&ShopNo=${this.data.labelName}*${this.data.labelPrice}*${this.data.ShopNo}`;
        var md5 = util.md5(str);
        var data = {
            bNo: 2202,
            LABLE_NAME: this.data.labelName,
            LABLE_PRICE: this.data.labelPrice,
            ShopNo: this.data.ShopNo,
            MD5: md5.toUpperCase()
        };

        request(data, res => {
            if (res.code === "100") {
                wx.showToast({
                    title: '添加成功',
                })
                this.setData({
                    Labellist: res.Labellist,
                    setTag: false,
                });
            } else {
                wx.showModal({
                    title: '提示',
                    content: data.msg,
                })
            }
        })
    },

    hideDialog() {
        this.setData({
            setTag: false,
        })
    },

    /**
     * 设置手机号
     */
    setTel(ev) {
        this.setData({
            keywords: ev.detail.value
        })
    },

    

    /**
     * 设置备注
     */
    setRemark(ev) {
        this.setData({
            remark: ev.detail.value
        })
    },

    openCwf() {
        this.setData({
            cwf: this.data.cwf == 0 ? 1 : 0,
        })
    },

    delTable(ev) {
        if (this.data.ztList.length > 1) {
            this.data.ztList.splice(ev.currentTarget.dataset.i, 1);
            wx.setStorage({
                key: 'zt_info',
                data: this.data.ztList,
            })
            this.setData({
                ztList: this.data.ztList
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前选择的桌台只剩最后一个，是否继续删除然后重新选择桌台？',
                success: res => {
                    if (res.confirm) {
                        wx.setStorage({
                            key: 'zt_info',
                            data: [],
                        })
                        wx.navigateBack({
                            delta: 1,
                        })
                    }
                }
            })
        }
    },

    getLabelInfo() {
        var str = `ShopNo=${this.data.ShopNo}`;
        var md5 = util.md5(str);
        var data = {
            bNo: 2201,
            ShopNo: this.data.ShopNo,
            MD5: md5.toUpperCase()
        };

        request(data, data => {
            wx.getStorage({
                key: 'label',
                success: res => {
                    for (var i = 0; i < data.Labellist.length; i++) {
                        if (res.data.ID == data.Labellist[i].ID) {
                            data.Labellist[i].checked = true;
                        } else {
                            data.Labellist[i].checked = false;
                        }
                    }
                    this.setData({
                        Labellist: data.Labellist,
                    })
                },
                fail: () => {
                    for (var i = 0; i < data.Labellist.length; i++) {
                        data.Labellist[i].checked = false;
                    }
                    this.setData({
                        Labellist: data.Labellist,
                    })
                }
            })
        })
    },

    chooseLabel(ev) {
        var index = ev.currentTarget.dataset.i;
        this.data.label = this.data.Labellist[index];
        this.data.Labellist[index].checked = !this.data.Labellist[index].checked;

        wx.setStorage({
            key: 'label',
            data: this.data.Labellist[index],
        })
        this.setData({
            Labellist: this.data.Labellist,
        })
    }
})